var app = getApp();
import {
  api,
  util,
  dialog,
  clearIncrement,
  storage
} from '../../../../js/util'
import {
  router
} from '../../../../js/router';
import {
  fastorder,
  orderlist,
  orderdetail,
  order
} from "../../../../js/modules/order.js"
const mall = require("../../../../js/modules/mall.js");
import {
  wholesaleSettings,
  config
} from "../../../../js/modules/gloab";
import {
  list
} from '../../../../js/modules/mall';
import authorize from '../../../../js/modules/authorize.js'
import BasePage from '../../../../js/common/base-page'
import { alert, deepMerge, isEmpty } from '../../../../js/newUtil';
BasePage({
  pageKey: "orderList",

  /**
   * 页面的初始数据
   */
  data: {
    imgDomain: api.imgDomain,
    enableOss: api.enableOss,
    tablist: ['全部', '待审核', '待支付', '待发货', '待收货', '已完成', '未付款', '取消中', '待提交', '已作废', '待评论'],
    activeIndex: 0,
    sliderOffset: 0,
    sliderLeft: 10,
    slidewidth: 70,
    showMerge: true,
    lists: [{
        status: -1, //全部
        list: [],
        hasMoreData: true,
        page: {
          PageIndex: 1,
          PageSize: 20,
          keywords: "",
          sortField: "",
          consigneeKeyword: '', //收货人/手机号
          consigneeAddress: '', //收货地址
          ProductKeyword: '', //商品关键字查询
          sortDirect: "desc"
        }
      },
      {
        status: 3, //待审核
        list: [],
        hasMoreData: true,
        page: {
          PageIndex: 1,
          PageSize: 20,
          keywords: "",
          sortField: "",
          consigneeKeyword: '', //收货人/手机号
          consigneeAddress: '', //收货地址
          ProductKeyword: '', //商品关键字查询
          sortDirect: "desc"
        }
      },
      {
        status: 1, //待支付
        list: [],
        hasMoreData: true,
        page: {
          PageIndex: 1,
          PageSize: 20,
          keywords: "",
          sortField: "",
          consigneeKeyword: '', //收货人/手机号
          consigneeAddress: '', //收货地址
          ProductKeyword: '', //商品关键字查询
          sortDirect: "desc"
        }
      },
      {
        status: 5, //待发货
        list: [],
        hasMoreData: true,
        page: {
          PageIndex: 1,
          PageSize: 20,
          keywords: "",
          sortField: "",
          consigneeKeyword: '', //收货人/手机号
          consigneeAddress: '', //收货地址
          ProductKeyword: '', //商品关键字查询
          sortDirect: "desc"
        }
      },
      {
        status: 6, //待收货
        list: [],
        hasMoreData: true,
        page: {
          PageIndex: 1,
          PageSize: 20,
          keywords: "",
          sortField: "",
          consigneeKeyword: '', //收货人/手机号
          consigneeAddress: '', //收货地址
          ProductKeyword: '', //商品关键字查询
          sortDirect: "desc"
        }
      }, {
        status: 7, //已完成
        list: [],
        hasMoreData: true,
        page: {
          PageIndex: 1,
          PageSize: 20,
          keywords: "",
          sortField: "",
          consigneeKeyword: '', //收货人/手机号
          consigneeAddress: '', //收货地址
          ProductKeyword: '', //商品关键字查询
          sortDirect: "desc"
        }
      }, {
        status: -2, //未付款
        list: [],
        hasMoreData: true,
        page: {
          PageIndex: 1,
          PageSize: 20,
          keywords: "",
          sortField: "",
          consigneeKeyword: '', //收货人/手机号
          consigneeAddress: '', //收货地址
          ProductKeyword: '', //商品关键字查询
          sortDirect: "desc"
        }
      }, {
        status: 11, //取消中
        list: [],
        hasMoreData: true,
        page: {
          PageIndex: 1,
          PageSize: 20,
          keywords: "",
          sortField: "",
          consigneeKeyword: '', //收货人/手机号
          consigneeAddress: '', //收货地址
          ProductKeyword: '', //商品关键字查询
          sortDirect: "desc"

        }
      }, {
        status: -5, //待提交
        list: [],
        hasMoreData: true,
        page: {
          PageIndex: 1,
          PageSize: 20,
          keywords: "",
          sortField: "",
          consigneeKeyword: '', //收货人/手机号
          consigneeAddress: '', //收货地址
          ProductKeyword: '', //商品关键字查询
          sortDirect: "desc"
        }
      }, {
        status: 8, //已取消
        list: [],
        hasMoreData: true,
        page: {
          PageIndex: 1,
          PageSize: 20,
          keywords: "",
          sortField: "",
          consigneeKeyword: '', //收货人/手机号
          consigneeAddress: '', //收货地址
          ProductKeyword: '', //商品关键字查询
          sortDirect: "desc"
        }
      }, {
        status: 70, //待评价
        list: [],
        hasMoreData: true,
        page: {
          PageIndex: 1,
          PageSize: 20,
          keywords: "",
          sortField: "",
          consigneeKeyword: '', //收货人/手机号
          consigneeAddress: '', //收货地址
          ProductKeyword: '', //商品关键字查询
          sortDirect: "desc"
        }
      }
    ],
    orderId: 0,
    display_total: "0",
    cancelValue: "现在不想购买",
    openComment: false,
    quantityDigits: 0,
    priceDigits: 2, //价格显示小数位数
    isPay: true, //是否能合并支付
    Initiator: 0,
    Currency: '', //货币符号
    showFilter: false, //是否显示筛选
    orderName: '', //收货人
    orderAddress: '', //收货人地址
    orderNum: '', //商品
    StartDeliveryTime: '', // 送货开始时间 - 筛选条件
    EndDeliveryTime: '', // 送货结束时间 - 筛选条件
    timePickerStart: '1970-01-01 08:00', // picker范围结束时间
    timePickerEnd: '2099-12-31 23:59', // picker范围结束时间
    CloseBuyerCancel: false, //禁止买家取消订单
    customFileds: [], //自定义订单
    customInfosList: [], //已填写的自定义订单
    orderData: false,
    scopeArray: ['线上', '全部'],
    scopeIndex: 0, //索引
    TravellingOrder: false, //线下
    offline: 0,
    tabWord: '', // 进入页面时的tab的名字，用于切换默认的tab
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log('purchase list onLoad')
    clearIncrement();
    let tabWord = options.tabWord || "全部";
    this.setData({
      tabWord
    })
    let scopeIndex = wx.getStorageSync('orderListFilterScopeIndex')
    if (!scopeIndex) {
      scopeIndex = 0
    }

    this.setData({
      Initiator: authorize.getEntity().manager ? authorize.getEntity().manager.Initiator : 0,
      offline: scopeIndex
    });
    this.getWholesaleConfig();
    this.cancelOrder = this.selectComponent("#cancelOrder");
    //加载订单自定义字段信息
    this.customizefields();
  },
  /**加载商品列表 */
  loadList() {
    var that = this;
    var current = this.data.lists[that.data.activeIndex];
    var param = current.page;
    param.orderData = this.formateOrderData();
    if (that.data.offline == 0) {
      orderlist.loadList(current.status, param, function (content, fkid) {
        var hasMoreData = content.count > (current.page.PageIndex) * current.page.PageSize;
        var list_key = "lists[" + that.data.activeIndex + "].list";
        //是否有更多数据
        var list_has = "lists[" + that.data.activeIndex + "].hasMoreData";
        //无数据时显示的信息
        var isLoadComplete = "lists[" + that.data.activeIndex + "].isLoadComplete";
        var index = that.data.lists[that.data.activeIndex].list.length;
        var data = content.data;
        for (var i = 0; i < data.length; i++) {
          data[i].show = false;
          var child = data[i].Children;
          for (var j = 0; j < child.length; j++) {
            if (child[j].RefuQuantity < child[j].SippingQuantity) {
              data[i].show = true;
            }
          }
        }
        //当分页大于1时，累加
        if (current.page.PageIndex > 1) {
          data = that.data.lists[that.data.activeIndex].list.concat(data);
        }
        //如果key为变量作为key值的时候要用[]包裹起来
        that.setData({
          [list_key]: data,
          [list_has]: hasMoreData,
          [isLoadComplete]: true
        });
      })
    } else {
      orderlist.offlineData(current.status, param, function (content, fkid) {
        var hasMoreData = content.count > (current.page.PageIndex) * current.page.PageSize;
        var list_key = "lists[" + that.data.activeIndex + "].list";
        //是否有更多数据
        var list_has = "lists[" + that.data.activeIndex + "].hasMoreData";
        //无数据时显示的信息
        var isLoadComplete = "lists[" + that.data.activeIndex + "].isLoadComplete";
        var data = content.data;
        //当分页大于1时，累加
        if (current.page.PageIndex > 1) {
          data = that.data.lists[that.data.activeIndex].list.concat(data);
        }
        //如果key为变量作为key值的时候要用[]包裹起来
        that.setData({
          [list_key]: data,
          [list_has]: hasMoreData,
          [isLoadComplete]: true
        });
      })
    }
  },
  /**加载商品类的配置项参数 */
  getWholesaleConfig() {
    var that = this;
    var config = wholesaleSettings.getConfig();
    var openComment = config.openComment;
    let tabWord = this.data.tabWord
    if (!openComment) {
      var index = -1;

      that.data.tablist.map(function (item, i) {
        if (item == "待评论") {
          index = i;
          return;
        }
      })
      that.data.tablist.splice(index, 1);
      that.data.lists.splice(index, 1);
    }
    var isStoreAffirmOrder = config.isStoreAffirmOrder;
    if (!isStoreAffirmOrder) {
      that.data.tablist.map(function (item, i) {
        if (item == "待提交") {
          index = i;
          return;
        }
      })
      that.data.tablist.splice(index, 1);
      that.data.lists.splice(index, 1);
    }
    var allOrderAudit = config.allOrderAudit;
    var cODOrderAudit = config.cODOrderAudit;
    var offlinePayOrderAudit = config.offlinePayOrderAudit;
    if (!allOrderAudit && !cODOrderAudit && !offlinePayOrderAudit) {
      that.data.tablist.map(function (item, i) {
        if (item == "待审核") {
          index = i;
          return;
        }
      })
      that.data.tablist.splice(index, 1);
      that.data.lists.splice(index, 1);
    }
    let activeIndex = that.data.tablist.indexOf(tabWord)
    let sliderLeft = 10 + activeIndex * that.data.slidewidth
    that.setData({
      quantityDigits: config.quantityDigits,
      priceDigits: config.priceDigits,
      openComment: openComment,
      tablist: that.data.tablist,
      lists: that.data.lists,
      tabWord: '',
      activeIndex,
      sliderLeft,
    });
    var fkid = app.dns.proprietorId;
    var fkflag = app.dns.proprietor;
    list.getWholesaleConfigs(
      fkid,
      fkflag,
      (content) => {
        // 如果没有上次的筛选信息，则默认线上
        let scopeIndex = wx.getStorageSync('orderListFilterScopeIndex')
        if (isEmpty(scopeIndex)) {
          scopeIndex = 0
        }
        that.setData({
          CloseBuyerCancel: content.CloseBuyerCancel,
          TravellingOrder: content.TravellingOrder,
          scopeIndex,
          offline: scopeIndex
        });
        wx.setStorageSync('orderListFilterScopeIndex', scopeIndex)
        this.loadList();
      })
  },
  /**
   * 关键词搜索
   */
  onSearchKeywordEvent: function (e) {
    this.cleanList(this);
    this.reset();
    for (var i = 0; i < this.data.lists.length; i++) {
      this.data.lists[i].page.keywords = e.detail;
    }
    this.loadList();
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    wx.stopPullDownRefresh();
    this.data.lists[this.data.activeIndex].page.PageIndex = 1;
    this.loadList();
    // console.log("onPullDownRefresh");
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function (e) {
    var current = this.data.lists[this.data.activeIndex];
    if (current.hasMoreData) {
      var index = this.data.lists[this.data.activeIndex].page.PageIndex;
      this.data.lists[this.data.activeIndex].page.PageIndex = index + 1;
      this.loadList();
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    console.log('purchase list onShow')
    this.setData({
      Currency: api.Currency || '￥'
    })
    this.wxConfirmReceiveEvent()
  },
  /**
   * 刷新页面
   */
  refreshPage() {
    this.loadList();
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    // console.log("hide");
    console.log('purchase list onHide')
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },


  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  /**
   * 切换当前选择项
   */
  onSwitchItem: function (res) {
    let {
      activeIndex,
      slidewidth,
      lists
    } = this.data;
    if (activeIndex == res.detail.currentNum.id) return;
    activeIndex = parseInt(res.detail.currentNum.id);
    this.setData({
      sliderLeft: 10 + activeIndex * slidewidth,
      activeIndex: activeIndex
    });
    var current = lists[activeIndex];
    // if (current.list == null || current.list.length == 0) {
    this.loadList();
    // }
  },

  /**
   * 展开遮罩层
   */
  showModal: function (e) {
    var id = e.currentTarget.dataset.orderid;
    this.cancelOrder.showModal(e, id);
  },
  /**
   * 选择取消原因
   *  */
  onCancelOrderEvent: function (e) {
    this.cleanList(this);
    this.loadList();
  },
  /**
   * 提交
   */
  submitOrder: function (e) {
    let that = this;
    let orderInfo = e.currentTarget.dataset.orderinfo;
    util.confirm(function () {
      let data = {
        OrderId: orderInfo.Id,
        AddressId: 0,
        PayTypeId: orderInfo.PayTypeId
      }
      orderdetail.submitOrder(data, function () {
        that.cleanList(that);
        that.loadList();
      });
    }, null, "是否确认提交订单？", "确认提交")
  },
  /**
   * 立即收货
   */
  onConfirmReceiveEvent: function (e) {
    var that = this;
    var orderid = e.currentTarget.dataset.orderid;
    var oddnumber = e.currentTarget.dataset.oddnumber;
    let OrderInfo = e.currentTarget.dataset.item || {}
    // 调用微信收货组件
    if (!isEmpty(OrderInfo.WxExtraData) && wx.openBusinessView) {
      order.getWxShippingInfo(orderid, function (res) {
        console.log(res)
        if (res.Success == false) {
          // 同步订单失败时,调用收货原逻辑
          // 比如用户已经在微信消息中确认收货了,就会同步失败
          orderlist.confirmReceive(oddnumber, function () {
            that.cleanList(that);
            that.loadList();
          });
          return
        }
        let extraData = OrderInfo.WxExtraData || {}
        wx.openBusinessView({
          businessType: "weappOrderConfirm",
          extraData: {
            transaction_id: extraData.TransactionId,
            merchant_id: extraData.MerchantId,
            merchant_trade_no: extraData.MerchantTradeNo,
            orderid,
            oddnumber
          },
          success (res) {
            console.log('weappOrderConfirm success', res)
          },
          fail (err) {
            console.log('weappOrderConfirm fail', err)
          }
        })
      })
      return
    }
    orderlist.confirmReceive(oddnumber, function () {
      that.cleanList(that);
      that.loadList();
    });
  },

  /**
   * 判断是否为微信确认收货组件,成功点击收货
   */
  wxConfirmReceiveEvent() {
    let that = this
    let activeIndex = this.data.activeIndex
    let list = this.data.lists || []
    if (!isEmpty(app.globalData.appShowData)) {
      let e = app.globalData.appShowData || {}
      // 场景值1038,从其他小程序返回(确认收货组件会使用navigateBackMiniProgram返回当前小程序)
      // 通过 app onshow中的参数来处理逻辑
      if (e.scene == 1038 && e.referrerInfo) {
        let referrerInfo = e.referrerInfo || {}
        let extraData = referrerInfo.extraData || {}
        let appId = referrerInfo.appId
        let status = extraData.status
        if (!isEmpty(extraData) && !isEmpty(list[activeIndex].list)) {
          // 当用户确认收货时 status 为success
          if (status != 'success') {
            return
          }
          let reqData = extraData.req_extradata || {}
          let oddnumber = reqData.oddnumber || '' // 订单信息
          let receiveOrderHistory = app.globalData.receiveOrderHistory || [] // 已经调用过确认收货的订单
          // 当已经调用过确认收货,则不再次调用
          if (oddnumber && !receiveOrderHistory.includes(oddnumber)) {
            orderlist.receiveNow(oddnumber, function () {
              app.globalData.receiveOrderHistory.push(oddnumber)
              that.cleanList(that)
              that.loadList()
            })
          }
        }
      }
    }
  },

  /*
  再次购买
   */
  onAginBuyEvent: function (e) {
    var id = e.currentTarget.dataset.orderid;
    fastorder.aginBuy(id);
  },
  /**
   * 删除订单
   */
  onDeleteEvent: function (e) {
    var that = this;
    var id = e.currentTarget.dataset.orderid;
    orderlist.deleteOrder(id, function () {
      that.cleanList(that);
      that.loadList();
    });
  },

  /**
   * 立即付款
   */
  onPayEvent: function(e) {
    let that = this
    var id = e.currentTarget.dataset.orderid;
    orderlist.onPay(id, function (res) {
        that.onPullDownRefresh()
    });
  },
  /**
   * 合并支付
   */
  onMergePayEvent: function (e) {
    if (!this.data.isPay) {
      util.alert("请选择同一种支付类型的订单进行支付");
      return;
    }
    orderlist.mergePay(this.data.orderids.join(","), this.data.payTypeId);
  },
  /**
   * 选择合并支付
   */
  onChoosetoPay: function (e) {
    var that = this;
    var _array = e.detail.value;
    var current = that.data.lists[that.data.activeIndex].list;
    var orderids = [];
    var total_price = 0,
      tatal_pay_integral = 0,
      total_deduction_integral = 0,
      payTypeId = 0;
    for (var i = 0; i < _array.length; i++) {
      var item = current[_array[parseInt(i)]];
      total_price += item.Payables;
      tatal_pay_integral += item.PayableIntegral;
      total_deduction_integral += item.DeductionIntegral;
      if (payTypeId != 0 && payTypeId != item.PayTypeId) {
        this.setData({
          isPay: false
        });
        util.alert("请选择同一种支付类型的订单进行支付");
        return;
      }
      payTypeId = item.PayTypeId;
      orderids.push(item.Id);
    }
    if (_array.length > 0) {
      var display = "0.00";
      if (total_price > 0 && tatal_pay_integral > 0) {
        display = that.data.Currency + total_price.toFixed(2) + "+" + tatal_pay_integral + "积分";
      } else if (total_price > 0) {
        display = that.data.Currency + total_price.toFixed(2);
      } else if (total_price > 0) {
        display = tatal_pay_integral + "积分";
      }
      if (total_deduction_integral > 0) {
        display += "可抵" + total_deduction_integral;
      }
      this.setData({
        showMerge: false,
        isPay: true,
        display_total: display,
        orderids: orderids,
        payTypeId: payTypeId
      });
    } else {
      this.setData({
        showMerge: true,
        isPay: true,
      });
    }
  },
  /**
   * 立即评价
   */
  onCommentEvent: function (e) {
    var that = this;
    let {
      activeIndex,
      tablist
    } = this.data;
    var oddnumber = e.currentTarget.dataset.oddnumber;
    //跳转到退换页面
    router.navigate({
      path: "comment",
      params: {
        oddNumber: oddnumber,
        pageParams: util.base64_encode("?tabWord=" + tablist[activeIndex])
      }
    });
  },
  /**
   * 申请售后
   */
  onApplyRetreatEvent: function (e) {
    var oddnumber = e.currentTarget.dataset.id;
    //跳转到退换页面
    router.navigate({
      path: "applyRetreat",
      params: {
        oddNumber: oddnumber
      }
    });
  },
  /**
   * 清除每一列
   */
  cleanList: function (that) {
    for (var i = 0; i < that.data.lists.length; i++) {
      that.data.lists[i].list = [];
      that.data.lists[i].page.PageIndex = 1;
    }
    that.setData({
      lists: that.data.lists
    });
  },
  onUnload: function (e) {
    this.data.pre_page = this.getPreData();
    if (this.data.pre_page) {
      this.data.pre_page.data.isBack = true;
    }
  },
  getPreData: function () {
    const pages = getCurrentPages();
    const length = pages.length;
    const prePage = pages[length - 2]; //上一页
    return prePage;
  },
  // 查看物流
  lookLogistics(e) {
    var orderid = e.currentTarget.dataset.orderid;
    var code = e.currentTarget.dataset.code;
    var name = e.currentTarget.dataset.name;
    router.navigate({
      path: "logisticsTracking",
      params: {
        id: orderid
      }
    })
  },

  /**
   * 点击筛选
   */
  onFilterEvent(e) {
    // this.filterComponent.get_category_screens();
    // this.filterComponent.reset();
    this.setData({
      showFilter: true
    });
  },
  /**
   * 关闭筛选
   */
  shutFilter: function () {
    this.setData({
      showFilter: false
    });
  },
  /**
   * 合同
   */
  bindContract: function (e) {
    var urls = e.currentTarget.dataset.url;
    urls = this.data.imgDomain + urls;
    wx.showModal({
      title: '温馨提示',
      content: '是否下载！！！',
      success(res) {
        if (res.confirm) {
          wx.downloadFile({
            url: urls, //仅为示例，并非真实的资源
            success(res) {
              var filePath = res.tempFilePath
              wx.openDocument({
                filePath: filePath,
                showMenu: true,
                success(con) {}
              })
            }
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  /**
   * 输入
   */
  iptName: function (e) {
    this.setData({
      orderName: e.detail.value, //收货人
    })
  },
  iptAddress: function (e) {
    this.setData({
      orderAddress: e.detail.value, //收货人地址
    })
  },
  iptNum: function (e) {
    this.setData({
      orderNum: e.detail.value, //商品
    })
  },
  changeDeliveryStartTime (e) {
    let value = e.detail
    this.setData({
      StartDeliveryTime: value
    })
  },
  changeDeliveryEndTime (e) {
    let value = e.detail
    this.setData({
      EndDeliveryTime: value
    })
  },
  /**
   * 确定
   */
  confirm: function () {
    var orderName = this.data.orderName;
    var orderAddress = this.data.orderAddress;
    var orderNum = this.data.orderNum;
    let {
      StartDeliveryTime,
      EndDeliveryTime
    } = this.data
    this.cleanList(this);
    for (var i = 0; i < this.data.lists.length; i++) {
      this.data.lists[i].page.consigneeKeyword = orderName;
      this.data.lists[i].page.consigneeAddress = orderAddress;
      this.data.lists[i].page.ProductKeyword = orderNum;
      if (StartDeliveryTime) {
        this.data.lists[i].page.StartDeliveryTime = StartDeliveryTime + ':00'
      }
      if (EndDeliveryTime) {
        this.data.lists[i].page.EndDeliveryTime = EndDeliveryTime + ':59'
      }
    }
    this.setData({
      showFilter: false,
      offline: this.data.scopeIndex
    });
    this.loadList();
    // console.log(orderName,orderAddress,orderNum,this.data.scopeIndex)
  },
  /**
   * 重置
   */
  reset: function () {
    // console.log(this.data.customFileds,'======45');
    // 重置时间选择器
    let pickerLength = 2
    for (let i = 0; i < pickerLength; i++) {
      const id = `#timePicer_${i}`
      const component = this.selectComponent(id)
      if (component) {
        if (component.clear) {
          component.clear()
        }
      }
    }
    this.setData({
      orderName: '',
      orderAddress: '',
      orderNum: '',
      customInfosList: [],
      StartDeliveryTime: '',
      EndDeliveryTime: '',
      customFileds: this.data.customFileds
    })
  },
  /**初始化订单自定义字段信息**/
  customizefields() {
    order.customizefields((res) => {
      if (res) {
        // 处理下拉、单选、多选显示的数据
        res.map((item) => {
          item.IsRequired = 0;
          item.Placeholder = '请输入' + item.FieldName;
          item.FieldName = item.FieldName + '：';
          item.value = '';
          if (item.FieldType === 'checkbox' || item.FieldType === 'select' || item.FieldType === 'radio') {

            let itemsValue = Object.keys(item.Items)
            let ItemList = []
            let flag = false
            if (item.FieldType === 'radio') {
              flag = true
            }
            itemsValue.map((vItem, index) => {
              let checkedStatus = false
              if (flag && index === 0) {
                checkedStatus = true
              }
              ItemList.push({
                key: vItem,
                value: item.Items[vItem],
                checked: checkedStatus
              })
            })
            item.ItemList = ItemList
          }
        })
        this.setData({
          customFileds: res
        })
      }
    })
  },
  // 组装自定义订单数组
  formateOrderData() {
    let list = {};
    let customInfosList = this.data.customInfosList // 已填写的信息
    customInfosList.map((item) => {
      let value = ''
      if (Array.isArray(item.value)) {
        value = item.value.join(',')
      } else {
        value = item.value
      }
      if (value) {
        list['Field_' + item.dataId] = value
      }
    })
    let finalXml = list
    return finalXml
  },
  /**
   * 自定义模块
   */
  // 输入框 文本域
  inputCallBack(e) {
    this.dealCustomInfosList(e)
  },
  // 处理自定义订单输入的公用方法
  dealCustomInfosList(event) {
    let value = event.detail
    if (!value) {
      wx.showToast({
        title: '数据格式错误',
        icon: 'none'
      })
      return
    }

    let customInfosList = this.data.customInfosList
    let flag = false
    if (customInfosList.length <= 0) {
      customInfosList.push(value)
      return
    }
    for (var i = 0; i < customInfosList.length; i++) {
      if (customInfosList[i].dataId === value.dataId) {
        customInfosList[i] = value
        flag = true
        break
      }
    }
    if (!flag) {
      customInfosList.push(value)
    }
    this.setData({
      customInfosList: customInfosList
    })
  },
  // 统计范围
  bindPickerChange(e) {
    this.setData({
      scopeIndex: Number(e.detail.value)
    })
    wx.setStorageSync('orderListFilterScopeIndex', Number(e.detail.value))
  },
  bindLook(e) {
    var num = e.currentTarget.dataset.orderid;
    router.navigate({
      path: "orderOffine",
      params: {
        oddNumber: num
      }
    });
  },
  /**
   * 订单按钮组件点击
   * @param {*} e 
   */
  orderButtonTap (e) {
    let method = e.detail.method
    let data = e.detail.data
    e.currentTarget.dataset = deepMerge(e.currentTarget.dataset, data)
    if (this[method]) {
      this[method](e)
    }
  }
})